package com.hmily.dubbo.provider.impl;

import com.hmily.dubbo.api.LongTimeQueryFacade;
import com.hmily.dubbo.api.UserQueryFacade;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.rpc.RpcContext;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * <h1>耗时操作的接口实现类。</h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2021-10-20
 *
 */
public class LongTimeQueryFacadeImpl implements LongTimeQueryFacade {

    @Override
    public String queryUser(String name) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String msg = "LongTimeQueryFacadeImpl, hello " + name + ", my name is yuki, my nickname is xyz. port: " + RpcContext.getContext().getLocalPort();
        System.out.println(msg);
        return msg;
    }

    @Override
    public String queryUser2(String name) {
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException("sleep interrupted error.", e);
        }
        String msg = "LongTimeQueryFacadeImpl, hello " + name + ", my name is yuki, my nickname is xyz. port: " + RpcContext.getContext().getLocalPort();
        System.out.println(msg);
        return msg;
    }

    @Override
    public String queryUserDumpStack(String name) {
        ThreadPool defaultExtension = ExtensionLoader.getExtensionLoader(ThreadPool.class).getDefaultExtension();

        Map<String, String> map = new HashMap<>();
        map.put("dump.directory", "E:\\OpenSource\\录制视频\\dubbo\\source\\dubbo-project");
        map.put("threadpool", "fixed");
        URL url = new URL("", "", 0, map);

        Executor executor = defaultExtension.getExecutor(url);

        for (int i = 0; i < 300; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        String msg = "LongTimeQueryFacadeImpl, hello " + name + ", my name is yuki, my nickname is xyz. port: " + RpcContext.getContext().getLocalPort();
        System.out.println(msg);
        return msg;
    }
}
